﻿using Microsoft.AspNetCore.Mvc;
using RAP.Web.Core.Server.Service.Common;
using RAP.Framework.Libary.DataSource;
using System;
using System.Threading.Tasks;
using RAP.Web.Libary.Controller;
using RAP.Web.Libary.Service.Session;
using RAP.Web.Libary.Common;
using RAP.Web.Libary.Authentication;
using RAP.Web.Libary.Controller.Attributes;

namespace RAP.Web.Core.Server.Controllers.Common
{
    /// <summary>
    /// 公共服务控制器
    /// </summary>
    public class CommonController : APIControllerBase
    {
        public CommonService CommonService { get; set; }

        public CommonController ( CommonService commonService )
        {
            CommonService = commonService;
        }

        /// <summary>
        /// 获取城市列表
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetCities ()
        {
            var res = await this.CommonService.GetCities();
            if ( res.HasError() )
            {
                return res;
            }
            return res.GetFirstList();
        }

        /// <summary>
        /// 初始化城市数据源
        /// </summary>
        /// <returns></returns>
        public async Task<object> InitCityDataSources ()
        {
            this.CommonService.InitCityDataSources();
            return await Task.FromResult( true );
        }

        /// <summary>
        /// 获取有效的城市编码
        /// </summary>
        /// <returns></returns>
        [NeedSession]
        public async Task<object> GetValidCityCode ()
        {
            return await this.CommonService.GetValidCityCode( this.QueryParams );
        }

        /// <summary>
        /// 获取省份数据
        /// </summary>
        /// <returns></returns>
        [NeedSession]
        public async Task<object> GetProvinces ()
        {
            return await this.CommonService.GetProvinces();
        }

        /// <summary>
        /// 获取开放的城市列表
        /// </summary>
        /// <returns></returns>
        [NeedSession]
        public async Task<object> GetOpenCitys ()
        {
            return await this.CommonService.GetOpenCitys();
        }

        /// <summary>
        /// 写入客户端日志
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NeedSession]
        public virtual async Task<object> WriteLog ()
        {
            await this.CommonService.WriteLog( this.QueryParams );
            return true;
        }

        [HttpGet]
        public object Timestamp ()
        {
            var now = DateTime.Now;
            return new
            {
                timestamp = DateTime.Now.GetTimestamp(),
                time = now.ToString( "yyyy-MM-dd HH:mm" )
            };
        }
    }
}
